Skip to main content

Perfect Squares

LeetCode 279 | Difficulty: Medium​

Medium

Problem Description​

Given an integer n, return the least number of perfect square numbers that sum to n.

A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not.

Example 1:

Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.

Example 2:

Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.

Constraints:

- `1 <= n <= 10^4`

Topics: Math, Dynamic Programming, Breadth-First Search


Approach​

Dynamic Programming​

Break the problem into overlapping subproblems. Define a state (what information do you need?), a recurrence (how does state[i] depend on smaller states?), and a base case. Consider both top-down (memoization) and bottom-up (tabulation) approaches.

When to use

Optimal substructure + overlapping subproblems (counting ways, min/max cost, feasibility).

BFS (Graph/Matrix)​

Use a queue to explore nodes level by level. Start from source node(s), visit all neighbors before moving to the next level. BFS naturally finds shortest paths in unweighted graphs.

When to use

Shortest path in unweighted graph, level-order processing, spreading/flood fill.

Mathematical​

Look for mathematical patterns or formulas. Consider: modular arithmetic, GCD/LCM, prime factorization, combinatorics, or geometric properties.

When to use

Problems with clear mathematical structure, counting, number properties.


Solutions​

Solution 1: C# (Best: 176 ms)​

MetricValue
Runtime176 ms
Memory59.5 MB
Date2019-12-27
Solution
public class Solution {
public int NumSquares(int n) {
List<int> squareNums = new List<int>();
for (int i = 1; i*i <= n; i++)
{
squareNums.Add(i*i);
}

int level = 0;
Queue<int> q = new Queue<int>();
q.Enqueue(n);
while(q.Count!=0)
{
level++;
int level_size = q.Count;
for (int i = 0; i < level_size; i++)
{
var remainder = q.Dequeue();
if(squareNums.Contains(remainder))
return level;
foreach (var square in squareNums)
{
if(remainder < square) continue;
q.Enqueue(remainder - square);
}
}
}

return -1;
}
}
πŸ“œ 1 more C# submission(s)

Submission (2019-12-27) β€” 192 ms, 59.4 MB​

public class Solution {
public int NumSquares(int n) {
List<int> squareNums = new List<int>();
for (int i = 1; i*i <= n; i++)
{
squareNums.Add(i*i);
}

int level = 0;
Queue<int> q = new Queue<int>();
q.Enqueue(n);
while(q.Count!=0)
{
level++;
int level_size = q.Count;
for (int i = 0; i < level_size; i++)
{
var remainder = q.Dequeue();
if(squareNums.Contains(remainder))
return level;
foreach (var square in squareNums)
{
if(remainder < square) continue;
q.Enqueue(remainder - square);
}
}
}

return -1;
}
}

Complexity Analysis​

ApproachTimeSpace
Dynamic Programming$O(n)$$O(n)$

Interview Tips​

Key Points
  • Discuss the brute force approach first, then optimize. Explain your thought process.
  • Define the DP state clearly. Ask: "What is the minimum information I need to make a decision at each step?"
  • Consider if you can reduce space by only keeping the last row/few values.